<?php

namespace app\admin\controller\mental;

use app\common\controller\Backend;
use think\Config;
use think\Db;

/**
 * 
 */
class Report extends Backend
{

    private $option = [
        'title' => [
            'text' => '报表'
        ],
        'tooltip' => [
            'trigger' => 'axis'
        ],
        'legend' => [
            'data' => []
        ],
        'grid' => [
            'left' => '3%',
            'right' => '4%',
            'bottom' => '3%',
            'containLabel' => true
        ],
        'toolbox' => [
            'feature' => [
                'saveAsImage' => []
            ]
        ],
        'xAxis' => [
            'type' => 'category',
            'boundaryGap' => false,
            'data' => [],
        ],
        'yAxis' => [
            'type' => 'value',
            'name' => '元'
        ],
        'series' => []
    ];

    public function index()
    {
        $totalorder = Db::name('mental_order')->count();
        $totalorderamount = Db::name('mental_order')->sum('amount');

        $totalpayorder = Db::name('mental_order')->where('status', 'paid')->count();
        $totalpayamount = Db::name('mental_order')->sum('payamount');

        $totalfinishtest = Db::name('mental_testlog')->where('status', 'finish')->count();
        $totalunfinishtest = Db::name('mental_testlog')->where('status', 'unfinish')->count();

        $this->view->assign([
            'totalpayorder'    => $totalpayorder,
            'totalpayamount'    => $totalpayamount,
            'totalorder'       => $totalorder,
            'totalorderamount' => $totalorderamount,
            'totalfinishtest' => $totalfinishtest,
            'totalunfinishtest' => $totalunfinishtest,
            'str_time'       => [
                '今天',
                '昨天',
                '本周',
                '上周',
                '本月',
                '上月',
                '最近七天',
                '最近一月',
                '最近三月',
                '最近半年',
                '最近一年'
            ]
        ]);
        return $this->view->fetch();
    }

    public function order()
    {
        $id = $this->request->param('id');
        $date_re = $this->getDateType($id);
        $xData = $this->getXData($date_re);

        $this->option['title']['text'] = "订单统计";
        $legend = [
            'order_all' => '全部',
            'order_nopay' => '待付款',
            'order_payed' => '已付款'
        ];
        $this->option['legend']['data'] = array_values($legend);
        $this->option['xAxis']['data'] = $xData['data'];

        foreach ($legend as $k => $v) {
            switch ($k) {
                case 'order_all':
                    $where = "
                            and createtime >" . $date_re['start'] . "
                            and createtime <" . $date_re['end'] . "
                        ";
                    $data = $this->getOrderData($date_re, $where, 'createtime');
                    break;
                case 'order_nopay':
                    $where = "
                            and createtime >" . $date_re['start'] . "
                            and createtime <" . $date_re['end'] . "
                            and status != 'paid'
                        ";
                    $data = $this->getOrderData($date_re, $where, 'createtime');
                    break;
                case 'order_payed':
                    $where = "
                            and paytime >" . $date_re['start'] . "
                            and paytime <" . $date_re['end'] . "
                            and status = 'paid'
                        ";
                    $data = $this->getOrderData($date_re, $where, 'paytime');
                    break;
            }
            if ($data['status']) {
                $this->option['series'][] = [
                    'name' => $v,
                    'type' => 'line',
                    'data' => array_column($data['data'], 'val')
                ];
            } else {
                $this->option['series'][] = [
                    'name' => $v,
                    'type' => 'line',
                    'data' => []
                ];
            }
        }
        $this->success('', '', $this->option);
    }

    //订单报表
    private function getOrderData($date_arr, $where, $join_val)
    {
        $result = [
            'status' => false,
            'data'   => [],
            'msg'    => '',
        ];
        $prefix = Config::get('database.prefix');
        $sql = "
            select shi_j.t,ifnull(sum(o.amount),0) as val,count(o.order_id) as num
            from
              (SELECT @a:=@a+1 as t from
                (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10) b1,
                (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10) b2,
                (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10) b3,
                (SELECT @a:=-1) b4 limit 0," . $date_arr['num'] . ") shi_j
            left join (
                select * from `" . $prefix . "mental_order` where 1=1 " . $where . " ) o 
                on shi_j.t = (( cast(o." . $join_val . " as signed) - " . $date_arr['start'] . ") div (" . $date_arr['section'] . "))
            group by shi_j.t
        ";
        $re = Db::query($sql);
        $result['data'] = $re;
        $result['sql'] = $sql;
        $result['status'] = true;
        return $result;
    }

    private function getXData(&$date_arr)
    {
        $result = [];
        $diff_day = $date_arr['end'] - $date_arr['start'];
        switch ($date_arr['section']) {
            case 1:                 //小时
                $section = 60 * 60;
                break;
            case 2:                 //天
                $section = 60 * 60 * 24;
                break;
            default: //天
                $section = 60 * 60 * 24;
        }
        //算x轴数据个数
        $x_nums = ceil($diff_day / $section);

        $date_arr['num'] = $x_nums;
        $date_arr['section'] = $section;

        $x_type = "";
        switch ($section) {
            case 3600:                 //小时
                if ($x_nums <= 24) {
                    $x_type = "H时";
                } elseif ($x_nums <= 720) {
                    $x_type = "d日H时";
                } else {
                    $x_type = "m月d日H时";
                }
                break;
            case 86400:                 //天
                if ($x_nums <= 31) {
                    $x_type = "d号";
                } elseif ($x_nums <= 365) {
                    $x_type = "m.d";
                } else {
                    $x_type = "Y.m.d";
                }
                break;
        }
        if ($x_type == "") {
           $this->error('选择类型');
        }

        for ($i = $date_arr['start']; $i < ($date_arr['end']); $i = $i + $date_arr['section']) {
            if ($date_arr['section'] == 3600) {
                $result['data'][] = date($x_type, $i + $date_arr['section']);      //小时是结尾的表示当前切片的时间
            } else {
                $result['data'][] = date($x_type, $i);       //天是开始表示当前切片的时间
            }
        }
        return $result;
    }

    //换算前台时间按钮
    private function getDateType($date_type)
    {
        $date_arr = [];
        switch ($date_type) {
            case 1:             //昨天
                $date_arr['start'] = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
                $date_arr['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
                $date_arr['section'] = 1;
                break;
            case 2:              //本周              
                $date_arr['start'] = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));
                $date_arr['end'] = time();
                $date_arr['section'] = 2;
                break;
            case 3:              //上周             
                $date_arr['start'] = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
                $date_arr['end'] = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
                $date_arr['section'] = 2;
                break;
            case 4:              //本月
                $date_arr['start'] = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $date_arr['end'] = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                $date_arr['section'] = 2;
                break;
            case 5:              //上月
                $date_arr['start'] = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
                $date_arr['end'] = strtotime(date('Y-m-01') . ' -1 day');
                $date_arr['section'] = 2;
                break;
            case 6:              //最近7天
                $date_arr['start'] = time() - 6 * 60 * 60 * 24;
                $date_arr['end'] = time();
                $date_arr['section'] = 2;
                break;
            case 7:              //最近一月
                $date_arr['start'] = strtotime('-1 month +1 day');
                $date_arr['end'] = time();
                $date_arr['section'] = 2;
                break;
            case 8:              //最近3月
                $date_arr['start'] = strtotime('-3 month +1 day');
                $date_arr['end'] = time();
                $date_arr['section'] = 2;
                break;
            case 9:              //最近6年
                $date_arr['start'] = strtotime('-6 month +1 day');
                $date_arr['end'] = time();
                $date_arr['section'] = 2;
                break;
            case 10:              //最近1年
                $date_arr['start'] = strtotime('-12 month +1 day');
                $date_arr['end'] = time();
                $date_arr['section'] = 2;
                break;

            default: //今天
                $date_arr['start'] = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $date_arr['end'] = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                $date_arr['section'] = 1;
        }
        return $date_arr;
    }
}
